package com.yvon.maple.auth.authorization.service.impl;

import com.yvon.maple.auth.authorization.model.SecurityUser;
import com.yvon.maple.auth.authorization.service.SecurityUserService;
import com.yvon.maple.cloud.api.system.dto.SecurityUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author : Yvon
 * @since : 2022-04-12
 */
@Slf4j
@Service("userDetailsService")
public class SecurityUserServiceImpl implements SecurityUserService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO
        SecurityUserDTO dto = new SecurityUserDTO(10086L, "$2a$10$1MX2u1FS5lPhqmkIaTe/FuYacqA19U5A2A7RWeO5uIJchl4Sjw/.e", "admin", true, true, true, true, null);
        SecurityUser securityUser = new SecurityUser(
                dto, getAuthorities(null));
        checkUser(securityUser);
        return securityUser;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(List<String> roleCodes) {
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (roleCodes != null) {
            roleCodes.forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }
        return authorities;
    }

    public void checkUser(SecurityUser securityUser) {
        if (!securityUser.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员!");
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定，请联系管理员!");
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期，请联系管理员!");
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("该账户的登录凭证已过期，请重新登录!");
        }
    }
}
